<template>
  <div class="section-indicators-table">
    <div class="chart-header">
      <span>{{ title || '全段指标动态' }}</span>
      <div class="filter-container" v-if="showExportButton">
        <el-button 
          type="primary" 
          size="small" 
          @click="exportExcel"
          icon="el-icon-download"
        >
          导出Excel
        </el-button>
      </div>
    </div>
    <div class="excel-table-container" style="padding: 15px; background: #f5f7fa; border-radius: 5px; overflow-x: visible; overflow-y: auto; max-height: 700px;">
      <table class="excel-style-table" style="width: 100%; border-collapse: collapse; background: white; border-radius: 5px; overflow: hidden; box-shadow: 0 2px 8px 0 rgba(0,0,0,.1); font-size: 13px;">
        <thead>
          <tr style="background-color: #ecf5ff; border-bottom: 1px solid #ebeef5;">
            <th style="width: 36px; padding: 4px 3px; text-align: center; vertical-align: middle; font-weight: 500; border-right: 1px solid #ebeef5; font-size: 13px; line-height: 1.4;">事项</th>
            <th style="width: 32px; padding: 4px 3px; text-align: center; vertical-align: middle; font-weight: 500; border-right: 1px solid #ebeef5; font-size: 13px; word-break: break-all; line-height: 1.4;">子项目</th>
            <th style="padding: 8px 10px; text-align: left; font-weight: 500; font-size: 13px; border-right: 1px solid #ebeef5;">选项统计</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="indicator in indicatorsData">
            <!-- 计算需要合并的行数：子项目数 + 选项数 -->
            <template v-if="indicator && indicator.optionSelections && indicator.optionSelections.length > 0">
              <tr class="category-row" :key="indicator.id + '-category'" style="background-color: #f7f8fa;">
                <td :rowspan="indicator.optionSelections.length" style="width: 36px; padding: 4px 3px; text-align: center; vertical-align: middle; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; font-weight: 500; font-size: 13px; line-height: 1.4;">{{ indicator.name || '' }}</td>
                <td style="width: 32px; padding: 4px 3px; text-align: center; vertical-align: middle; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; font-size: 13px; word-break: break-all; line-height: 1.4;">{{ indicator.optionSelections[0] && indicator.optionSelections[0].name || '' }}</td>
                <td style="padding: 8px 10px; text-align: left; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; font-size: 13px;">
                  <div v-if="indicator.optionSelections[0] && indicator.optionSelections[0].options && indicator.optionSelections[0].options.length > 0" class="inline-options">
                    <span v-for="(option, optionIndex) in indicator.optionSelections[0].options" :key="indicator.id + '-project-0-option-' + optionIndex" class="inline-option">
                      <span class="option-text">{{ option.name || '' }}:</span>
                      <span class="count-text">{{ option.count || 0 }}</span>
                      <span v-if="option.unit" style="margin-left: 2px;">{{ option.unit }}</span>
                      <span class="percentage-text">{{ option.percentage ? parseInt(option.percentage) : 0 }}%</span>
                      <span v-if="optionIndex < (indicator.optionSelections[0].options.length - 1)" style="margin: 0 10px; color: #c0c4cc;">|</span>
                    </span>
                  </div>
                </td>
                <!-- 指标治理列隐藏，仅在导出Excel时显示 -->
              </tr>
              <!-- 处理剩余子项目 -->
              <template v-for="(subProject, projectIndex) in indicator.optionSelections" v-if="projectIndex > 0">
                <tr class="category-row" style="border-bottom: 1px solid #ebeef5; background-color: #f7f8fa;">
                  <td style="width: 32px; padding: 4px 3px; text-align: center; vertical-align: middle; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; font-size: 13px; font-weight: 500; word-break: break-all; line-height: 1.4;">{{ subProject && subProject.name || '' }}</td>
                  <td style="padding: 8px 10px; text-align: left; border-right: 1px solid #ebeef5; border-bottom: 1px solid #ebeef5; font-size: 13px;">
                    <div v-if="subProject && subProject.options && subProject.options.length > 0" class="inline-options">
                        <span v-for="(option, optionIndex) in subProject.options" :key="indicator.id + '-project-' + projectIndex + '-option-' + optionIndex" class="inline-option">
                          <span class="option-text">{{ option.name || '' }}:</span>
                          <span class="count-text">{{ option.count || 0 }}</span>
                          <span v-if="option.unit" style="margin-left: 2px;">{{ option.unit }}</span>
                          <span class="percentage-text">{{ option.percentage ? parseInt(option.percentage) : 0 }}%</span>
                          <span v-if="optionIndex < (subProject.options.length - 1)" style="margin: 0 10px; color: #c0c4cc;">|</span>
                        </span>
                      </div>
                    </td>
                    <!-- 指标治理列隐藏，仅在导出Excel时显示 -->
                  </tr>
              </template>
            </template>
          </template>
        </tbody>
      </table>
      <div v-if="indicatorsData.length === 0" class="no-data" style="text-align: center; padding: 20px; color: #909399; font-size: 13px;">
        暂无数据
      </div>
    </div>
  </div>
</template>

<script>
import api from "@/utils/api.js";

export default {
  name: "SectionIndicatorsTable",
  props: {
    // 查询日期
    queryDate: {
      type: [Date, String],
      default: () => new Date()
    },
    // 年段ID
    sectionId: {
      type: String,
      default: "1"
    },
    // 表格标题
    title: {
      type: String,
      default: "全段指标动态"
    },
    // 是否显示导出按钮
    showExportButton: {
      type: Boolean,
      default: true
    },
    // 幼儿园名称
    kindergartenName: {
      type: String,
      default: "当前幼儿园"
    }
  },
  data() {
    return {
      // 指标数据
      indicatorsData: []
    };
  },
  watch: {
    // 监听日期变化，重新加载数据
    queryDate: {
      handler(newDate) {
        this.loadSectionIndicators();
      },
      deep: true
    },
    // 监听年段ID变化，重新加载数据
    sectionId: {
      handler(newSectionId) {
        this.loadSectionIndicators();
      }
    }
  },
  mounted() {
    // 组件挂载后加载数据
    this.loadSectionIndicators();
  },
  methods: {
    // 加载年段指标配置
    loadSectionIndicators() {
      // 构建请求参数
      const params = {
        date: this.formatDate(this.queryDate),
        sectionId: this.sectionId
      };
      
      // 调用API获取当前年段的选项统计数据
      this.$fetch(api.getSectionIndicators, params)
        .then((response) => {
          console.log(response, '年段选项统计数据');
          if (response.code === 0 && response.data && Array.isArray(response.data)) {
            // 解析数据
            this.indicatorsData = this.parseOptionStatsData(response.data);
          } else {
            this.indicatorsData = [];
          }
        })
        .catch((err) => {
          console.error('获取年段选项统计数据失败:', err);
          this.indicatorsData = [];
        });
    },
    
    // 解析选项统计数据
    parseOptionStatsData(data) {
      console.log('原始选项统计数据:', data);
      const result = [];
      
      try {
        // 增加数据有效性检查
        if (!data || !Array.isArray(data)) {
          console.error('数据格式错误，期望数组格式');
          return [];
        }
        
        // 遍历顶层分类（事项）
        data.forEach(category => {
          // 确保分类是有效对象
          if (!category || !category.name) return;
          
          const indicator = {
            id: category.id,
            name: category.name, // 事项名称
            optionSelections: [],
            avgValue: category.avgValue || 0
          };
          
          // 优先处理optionHierarchy数据（层级结构）
          if (category.optionHierarchy && Array.isArray(category.optionHierarchy)) {
            category.optionHierarchy.forEach(hierarchyItem => {
              if (hierarchyItem.name) {
                const subProject = {
                  name: hierarchyItem.name,
                  options: []
                };
                
                // 处理选项数据
                if (hierarchyItem.subOptions && Array.isArray(hierarchyItem.subOptions)) {
                  hierarchyItem.subOptions.forEach(option => {
                    // 支持option或name字段作为选项名称
                    const optionName = option.option || option.name;
                    if (optionName) {
                      subProject.options.push({
                        name: optionName,
                        count: option.count || 0,
                        percentage: option.percentage || 0,
                        unit: ''
                      });
                    }
                  });
                }
                
                indicator.optionSelections.push(subProject);
              }
            });
          } else if (category.optionSelections && Array.isArray(category.optionSelections)) {
            // 按主选项分组
            const optionGroups = {};
            
            category.optionSelections.forEach(optionSelection => {
              if (!optionSelection.option) return;
              
              // 获取主选项名称作为子项目名称
              const subProjectName = optionSelection.option;
              
              if (!optionGroups[subProjectName]) {
                optionGroups[subProjectName] = {
                  name: subProjectName, // 使用option作为子项目名称
                  options: [] // 子项目的选项数组
                };
              }
              
              // 处理子项目（subOptions）
              if (optionSelection.subOptions && Array.isArray(optionSelection.subOptions)) {
                optionSelection.subOptions.forEach(subOpt => {
                  // 支持option或name字段作为选项名称
                  const optionName = subOpt.option || subOpt.name;
                  if (optionName) {
                    optionGroups[subProjectName].options.push({
                      name: optionName,
                      count: subOpt.count || 0,
                      percentage: subOpt.percentage || 0,
                      unit: ''
                    });
                  }
                });
              }
            });
            
            // 将分组后的子项目添加到indicator中
            for (const key in optionGroups) {
              indicator.optionSelections.push(optionGroups[key]);
            }
          }
          
          // 确保即使没有子项目，也添加一个默认的子项目结构
          if (indicator.optionSelections.length === 0) {
            indicator.optionSelections.push({
              name: '暂无数据', // 默认子项目名称
              options: [] // 空选项数组
            });
          }
          
          // 即使没有子项目，也要添加主选项到结果中
          result.push(indicator);
        });
        
        return result;
      } catch (error) {
        console.error('解析选项统计数据出错:', error);
        return [];
      }
    },
    
    // 导出Excel
    exportExcel() {
      try {
        // 显示加载中提示
        this.$message({
          message: '正在导出Excel，请稍候...',
          type: 'info',
          duration: 0,
          showClose: true
        });
        
        // 导入xlsx库
        const XLSX = require('xlsx');
        
        // 准备表头信息
        const kindergartenName = this.kindergartenName || '当前幼儿园';
        const sectionName = this.getSectionName(this.sectionId);
        const reportDate = this.formatDate(this.queryDate);
        
        // 创建完整的数据数组
        const fullData = [];
        
        // 添加报表标题行
        fullData.push([`${kindergartenName}${sectionName}${reportDate}日反馈治理报表`]);
        
        // 添加空行
        fullData.push(['']);
        
        // 添加表头行
        fullData.push(['事项', '子项目', '选项统计', '指标治理']);
        
        // 直接从indicatorsData生成数据行
        if (this.indicatorsData && this.indicatorsData.length > 0) {
          this.indicatorsData.forEach(indicator => {
            if (!indicator || !indicator.optionSelections || indicator.optionSelections.length === 0) {
              return;
            }
            
            indicator.optionSelections.forEach((subProject, index) => {
              const row = [];
              
              // 第一行显示事项名称，后续行留空
              if (index === 0) {
                row.push(indicator.name || '');
              } else {
                row.push('');
              }
              
              // 子项目名称
              row.push(subProject && subProject.name || '');
              
              // 选项统计
              let optionsText = '';
              if (subProject && subProject.options && subProject.options.length > 0) {
                optionsText = subProject.options.map(option => {
                  let text = `${option.name || ''}: ${option.count || 0}`;
                  if (option.unit) text += option.unit;
                  text += ` (${option.percentage ? parseInt(option.percentage) : 0}%)`;
                  return text;
                }).join(' | ');
              }
              row.push(optionsText);
              
              // 指标治理
              if (index === 0) {
                row.push(indicator ? this.calculateGovernanceLevel(indicator) : '暂无数据');
              } else {
                row.push(this.calculateSubProjectGovernance(subProject));
              }
              
              fullData.push(row);
            });
          });
        }
        
        // 创建工作表
        const ws = XLSX.utils.aoa_to_sheet(fullData);
        
        // 设置列宽
        ws['!cols'] = [
          { wch: 15 }, // 事项列
          { wch: 15 }, // 子项目列
          { wch: 40 }, // 选项统计列（较宽）
          { wch: 12 }  // 指标治理列
        ];
        
        // 合并报表标题行
        ws['!merges'] = [
          {
            s: { r: 0, c: 0 },
            e: { r: 0, c: 3 }
          }
        ];
        
        // 创建工作簿
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '指标治理报表');
        
        // 生成Excel文件并下载
        const fileName = `${kindergartenName}${sectionName}日反馈治理报表_${reportDate}.xlsx`;
        XLSX.writeFile(wb, fileName);
        
        // 关闭加载提示并显示成功消息
        this.$message.closeAll();
        this.$message.success('Excel导出成功');
      } catch (error) {
        this.$message.closeAll();
        console.error('导出Excel失败:', error);
        this.$message.error('导出失败，请稍后重试');
      }
    },
    
    // 获取年段名称
    getSectionName(id) {
      const sectionMap = {
        '1': '小班',
        '2': '中班',
        '3': '大班'
      };
      return sectionMap[id] || '未知年段';
    },
    
    // 准备Excel数据
    prepareExcelData() {
      const data = [];
      
      // 表头部分
      const kindergartenName = this.kindergartenName || '当前幼儿园';
      const sectionName = this.getSectionName(this.sectionId);
      const reportDate = this.formatDate(this.queryDate);
      
      // 表格数据部分（不包含表头，表头在createWorkbook中单独处理）
      // 添加表格标题行
      data.push(['事项', '子项目', '选项统计', '指标治理']);
      
      // 添加数据行
      if (this.indicatorsData && this.indicatorsData.length > 0) {
        this.indicatorsData.forEach(indicator => {
          if (!indicator || !indicator.optionSelections || indicator.optionSelections.length === 0) {
            return;
          }
          
          indicator.optionSelections.forEach((subProject, index) => {
            const row = [];
            
            // 第一行显示事项名称，后续行留空
            if (index === 0) {
              row.push(indicator.name || '');
            } else {
              row.push('');
            }
            
            // 子项目名称
            row.push(subProject && subProject.name || '');
            
            // 选项统计
            let optionsText = '';
            if (subProject && subProject.options && subProject.options.length > 0) {
              optionsText = subProject.options.map(option => {
                let text = `${option.name || ''}: ${option.count || 0}`;
                if (option.unit) text += option.unit;
                text += ` (${option.percentage ? parseInt(option.percentage) : 0}%)`;
                return text;
              }).join(' | ');
            }
            row.push(optionsText);
            
            // 指标治理
            if (index === 0) {
              row.push(indicator ? this.calculateGovernanceLevel(indicator) : '暂无数据');
            } else {
              row.push(this.calculateSubProjectGovernance(subProject));
            }
            
            data.push(row);
          });
        });
      }
      
      return data;
    },
    
    // 准备Excel数据（保留此方法以兼容其他可能的调用）
    prepareExcelData() {
      const data = [];
      
      // 添加表格标题行
      data.push(['事项', '子项目', '选项统计', '指标治理']);
      
      // 添加数据行
      if (this.indicatorsData && this.indicatorsData.length > 0) {
        this.indicatorsData.forEach(indicator => {
          if (!indicator || !indicator.optionSelections || indicator.optionSelections.length === 0) {
            return;
          }
          
          indicator.optionSelections.forEach((subProject, index) => {
            const row = [];
            
            // 第一行显示事项名称，后续行留空
            if (index === 0) {
              row.push(indicator.name || '');
            } else {
              row.push('');
            }
            
            // 子项目名称
            row.push(subProject && subProject.name || '');
            
            // 选项统计
            let optionsText = '';
            if (subProject && subProject.options && subProject.options.length > 0) {
              optionsText = subProject.options.map(option => {
                let text = `${option.name || ''}: ${option.count || 0}`;
                if (option.unit) text += option.unit;
                text += ` (${option.percentage ? parseInt(option.percentage) : 0}%)`;
                return text;
              }).join(' | ');
            }
            row.push(optionsText);
            
            // 指标治理
            if (index === 0) {
              row.push(indicator ? this.calculateGovernanceLevel(indicator) : '暂无数据');
            } else {
              row.push(this.calculateSubProjectGovernance(subProject));
            }
            
            data.push(row);
          });
        });
      }
      
      return data;
    },
    
    // 计算指标治理等级
    calculateGovernanceLevel(indicator) {
      // 如果有avgValue字段，直接使用
      if (indicator.avgValue) {
        if (indicator.avgValue >= 80) return '优秀';
        if (indicator.avgValue >= 60) return '良好';
        return '待提升';
      }
      
      // 基于选项百分比计算
      let totalPercentage = 0;
      let validCount = 0;
      
      if (indicator.optionSelections && indicator.optionSelections.length > 0) {
        indicator.optionSelections.forEach(subProject => {
          if (subProject.options && subProject.options.length > 0) {
            // 只考虑前两个选项（通常是正面评价）
            const topOptions = subProject.options.slice(0, 2);
            topOptions.forEach(option => {
              if (option.percentage) {
                totalPercentage += option.percentage;
                validCount++;
              }
            });
          }
        });
      }
      
      // 计算平均百分比
      const avgPercentage = validCount > 0 ? totalPercentage / validCount : 0;
      
      if (avgPercentage >= 80) return '优秀';
      if (avgPercentage >= 60) return '良好';
      return '待提升';
    },
    
    // 计算子项目的治理等级
    calculateSubProjectGovernance(subProject) {
      if (!subProject || !subProject.options || subProject.options.length === 0) {
        return '暂无数据';
      }
      
      // 计算前两个选项的百分比总和（通常是正面评价）
      let positivePercentage = 0;
      const topOptions = subProject.options.slice(0, 2);
      
      topOptions.forEach(option => {
        positivePercentage += option.percentage || 0;
      });
      
      if (positivePercentage >= 80) return '优秀';
      if (positivePercentage >= 60) return '良好';
      return '待提升';
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      // 确保date是有效的日期字符串或Date对象
      const d = typeof date === 'string' && date.trim() 
        ? new Date(date)
        : date instanceof Date ? date : new Date();
      
      // 检查日期是否有效
      if (isNaN(d.getTime())) return '';
      
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.section-indicators-table {
  width: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 10px;
}

.filter-container {
  display: flex;
  gap: 10px;
}

.inline-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.inline-option {
  display: inline-flex;
  align-items: center;
}

.option-text {
  font-weight: 500;
  color: #606266;
}

.count-text {
  color: #1890ff;
  font-weight: bold;
  margin: 0 4px;
}

.percentage-text {
  color: #67c23a;
  font-weight: bold;
  margin-left: 4px;
}
</style>